package com.brayan.webapp.service.auxilliary;

import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

@Stateless
public class MailBean {

	@Inject
	transient private Logger LOGGER;
	private String EMAIL_REGEX = "^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+)*$";

	@Resource(name = "java:jboss/mail/Default")
	private Session mailSession;

	final String ADMIN_EMAIL = "palma@brayan.com";

	@Asynchronous
	public void send(String addresses, String topic, String textMessage, boolean sendBccToAdmin) {
		try {
			MimeMessage message = new MimeMessage(mailSession);
			message.setFrom("palma@brayan.com");
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));
			// Send a copy for every single
			message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(ADMIN_EMAIL));
			message.setSubject(topic, "UTF-8");
			message.setText(textMessage, "UTF-8");

			Transport transport = mailSession.getTransport();
			transport.connect();
			transport.send(message);

		} catch (MessagingException ex) {
			LOGGER.error("Cannot send mail to " + addresses + ". Error: " + ex.getMessage(), ex);
		}
		LOGGER.info("Successfully send mail to " + addresses + " on topic " + topic);
	}

	/**
	 * Send message and do NOT BCC the admin user. If you do want to bcc the admin,
	 * user {@link #send(String, String, String, boolean)}.
	 * 
	 * @param addresses
	 * @param topic
	 * @param textMessage
	 */
	@Asynchronous
	public void send(String addresses, String topic, String textMessage) {
		send(addresses, topic, textMessage, false);
	}

	public boolean isValidEmailAddress(String email) {
		if (email == null)
			return false;
		else
			return email.matches(EMAIL_REGEX);
	}
}
